﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Master/Dialog.Master" AutoEventWireup="true"
    CodeBehind="BillView.aspx.cs" Inherits="Warehouse.Web.Purchase.BillView" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style type="text/css">
        .billwrapper > * {
            width: 100%;
        }
        .billwrapper .infotable tr td:nth-child(1), .billwrapper .infotable tr td:nth-child(3) {
            width: 70px;
        }
        .billwrapper .infotable tr td:nth-child(2) {
            width: 160px;
        }
        p label {
            margin: 0 5px;
        }
        .purchasebill td:nth-child(1), .infotable td:nth-child(3) {
            width: 80px;
        }
        .purchasebill td:nth-child(2) {
            width: 160px;
        }
        .purchasebill td {
            padding: 0;
            height: 30px;
        }
        .purchasebill td > input[type="text"] {
            width: 100%;
        }
        #detailstable td {
            padding: 0;
        }
        #detailstable input[disabled] {
            background: transparent;
        }
        #detailstable input[type="text"] {
            width: 100%;
            margin: 0;
            border: 0;
            height: 22px;
        }
        #detailstable .col-sn {
            width: 30px;
            padding: 0 5px;
        }
        .col-product {
            width: 200px;
        }
        .col-unit {
            width: 40px;
        }
        .col-specification {
            width: 60px;
        }
        .col-price {
            width: 40px;
        }
        .col-count {
            width: 40px;
        }
        .col-amount {
            width: 60px;
        }
        .col-comments {
        }
        .gift .col-price, .gift .col-amount {
            width: 0;
            border: 0;
            padding: 0;
            max-width: 0;
        }
        .gift .col-count {
            border-right: 0;
            border-left: 0;
        }
        .gift .col-price label, .gift .col-amount label {
            display: none;
        }
    </style>

    <script type="text/javascript">
        var AllSupplier = {};
        var AllProducts = {};

        function getBill() {

            var bill = Util.getFields('.purchasebill');
            bill.HouseID = bill.HouseID - 0;
            bill.SupplierID = bill.SupplierID - 0;

            if (!bill.SerialNumber) {
                alert('请输入单据号');
                return;
            }
            if (!bill.HouseID) {
                alert('请选择仓库');
                return;
            }
            if (!bill.SupplierID) {
                alert('请选择供货商');
                return;
            }
            if (!bill.Transactor) {
                alert('请选择经手人');
                return;
            }

            var detaillist = [];
            var err = "";
            $.each($("#detailstable tbody tr"), function() {
                var detail = Util.getFields(this);
                detail.ProductSpecificationID = detail.ProductSpecificationID - 0;
                if (detail.ProductSpecificationID) {
                    if (isNaN(detail.Count) || isNaN(detail.Price) || isNaN(detail.Amount)) {
                        err = "数量、单价、金额必须为数字";
                    } else {
                        detail.Count = detail.Count - 0;
                        detail.Price = detail.Price - 0;
                        detail.Amount = detail.Amount - 0;
                        detail.ID = detail.ID - 0;
                        if (detail.Count < 1) {
                            err = "数量必须大于0";
                        } else if (detail.Price < 0) {
                            err = "单价不能为负数";
                        } else if (detail.Amount < 0) {
                            err = "金额不能为负数";
                        } else {
                            detaillist.push(detail);
                        }
                    }
                }
            });
            if (err) {
                alert(err);
                return;
            }
            if (detaillist.length == 0) {
                alert('请输入产品');
                return;
            }

            var payment = Util.getFields('.payment');
            payment.AccountID = payment.AccountID - 0;
            payment.Amount = payment.Amount - 0;
            if (payment.AccountID || payment.Amount) {
                if (!payment.AccountID) {
                    alert('请选择付款账户');
                    return;
                }
                if (payment.Amount <= 0) {
                    alert('付款金额必须大于0');
                    return;
                }
            } else {
                payment = null;
            }
            return { Bill: bill, Details: detaillist, Payment: payment };
        }

        function addBill(action) {
            var data = getBill();
            Util.post('', { action: action, Bill: JSON.stringify(data.Bill), Details: JSON.stringify(data.Details), Payment: JSON.stringify(data.Payment) }, function(succeed, data, err) {
                if (succeed) {
                    alert('保存成功');
                    dialogCallback(true);
                } else {
                    alert(err);
                }
            }, { autoOverlay: true });
        }

        function saveBill(action) {
            var bill = Util.getFields('.purchasebill');
            var data = { Bill: { ID: bill.ID, Summary: bill.Summary, Comments: bill.Comments }, Details: [] };

            $.each($("#detailstable tbody tr"), function() {
                var detail = Util.getFields(this);
                if (detail.ID) {
                    data.Details.push({ ID: detail.ID, Comments: detail.Comments });
                }
            });

            Util.post('', { action: action, Bill: JSON.stringify(data.Bill), Details: JSON.stringify(data.Details) }, function(succeed, data, err) {
                if (succeed) {
                    alert('保存成功');
                    dialogCallback(true);
                } else {
                    alert(err);
                }
            }, { autoOverlay: true });
        }

        function invalidBill(action) {
            if (confirm("确认作废此单据？")) {
                Util.post('', { action: action, ID: $('.purchasebill [field="ID"]').val() }, function(succeed, data, err) {
                    if (succeed) {
                        alert('作废成功');
                        dialogCallback(true);
                    } else {
                        alert(err);
                    }
                }, { autoOverlay: true });
            }
        }

        function updateSpecification(tr, data, setname, ignoreprice) {
            tr = $(tr);
            if (!data) {
                tr.find('[field="Count"]').val("");
                tr.find('[field="Amount"]').val("");
                tr.find(".txtproduct").val("");
            } else if (setname) {
                tr.find(".txtproduct").val([data.Name, data.Grade, data.Model].join(" "));
            }
            data = data || {};
            tr.find('[field="ProductSpecificationID"]').val(data.ID || "");
            tr.find('.col-specification input[type="text"]').val(data.Specification || "");
            tr.find('.col-unit input[type="text"]').val(data.Unit || "");
            if (!ignoreprice) {
                tr.find('[field="Price"]').val((!isNaN(data._PurchasePrice) ? data._PurchasePrice : data.PurchasePrice) || "");
            }
        }

        function getPrice() {
            if (!isNaN(window.Price)) {
                $.each(AllProducts, function() {
                    this['_PurchasePrice'] = window.Price;
                });
                return;
            }
            $.each(AllProducts, function() {
                delete this['_PurchasePrice'];
            });
            Util.get('', { action: "GetPrice", SupplierID: $('.purchasebill [field="SupplierID"]').val() - 0 }, function(succeed, data, err) {
                if (succeed) {
                    $.each(data, function() {
                        if (AllProducts[this.ProductSpecificationID]) {
                            AllProducts[this.ProductSpecificationID]['_PurchasePrice'] = this.PurchasePrice;
                        }
                    });
                }
            });
        }

        function getInventory() {
            $.each(AllProducts, function() {
                delete this['_Count'];
            });
            Util.get('', { action: "GetInventory", HouseID: $('[field="HouseID"]').val() - 0 }, function(succeed, data, err) {
                if (succeed) {
                    $.each(data, function() {
                        if (AllProducts[this.ProductSpecificationID]) {
                            AllProducts[this.ProductSpecificationID]['_Count'] = this.Count;
                        }
                    });
                }
            });
        }

        function calculateSpecification(tr, updatebill) {
            tr = $(tr);
            var price = tr.find('[field="Price"]').val() - 0;
            var count = tr.find('[field="Count"]').val() - 0;

            if (isNaN(price) || isNaN(count)) {
                alert("单价和数量必须是数字");
            } else {
                var amount = price * count;
                tr.find('[field="Amount"]').val(amount || '');
                if (updatebill) {
                    calculateBill();
                }
            }
        }

        function calculateBill() {
            var totalAmount = 0;
            var totalCount = 0;
            $('#detailstable tr').each(function() {
                var tr = $(this);
                totalAmount += (tr.find('[field="Amount"]').val() || '') - 0;
                totalCount += (tr.find('[field="Count"]').val() || '') - 0;
            });
            $('#txtTotalAmount').val(totalAmount);
            $('#txtTotalCount').val(totalCount);
        }
        $(function() {
            AllSupplier = Util.loadObjects("#allsupplier", "ID");
            AllProducts = Util.loadObjects("#allproducts", "ID");

            if (window.EditModel) {
                $('input[type="text"]').attr('readonly', 'readonly');
                $('select').attr('disabled', 'disabled');
                $('[field="Comments"],[field="Summary"]').removeAttr('readonly', 'readonly');
                $('#txtSupplier').val((AllSupplier[$('[field="SupplierID"]').val()] || { Name: '' }).Name);
            } else {
                $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });

                $('#txtSupplier').autocomplete({ autoFocus: true, delay: 10,
                    source: (function() {
                        var arr = [];
                        for (var k in AllSupplier) {
                            var p = AllSupplier[k];
                            arr.push({ label: p.Name + " " + p.Code, value: p.Name, data: p });
                        };
                        return arr;
                    })(),
                    select: function(event, ui) {
                        $('.purchasebill [field="SupplierID"]').val(ui.item.data.ID);
                        getPrice();
                    }
                }).bind('blur', function() {
                    var s = AllSupplier[$('.purchasebill [field="SupplierID"]').val()];
                    if (!s || s.Name != $(this).val()) {
                        $(this).val('');
                        $('.purchasebill [field="SupplierID"]').val('');
                    }
                });

                $('.txtproduct').autocomplete({ autoFocus: true, delay: 10,
                    source: function(request, response) {
                        var arr = [];
                        var reg = new RegExp(request.term, "i");
                        $.each(AllProducts, function() {
                            if (reg.test([this.Code, this.Name, this.Grade, this.Model, this.Specification].join(" "))) {
                                arr.push({
                                    label: [this.Code, this.Name, this.Grade, this.Model, this.Specification, "[" + (this._Count || 0) + "]"].join(" "),
                                    value: [this.Name, this.Grade, this.Model].join(" "),
                                    data: this
                                });
                            }
                        });
                        response(arr);
                    },
                    select: function(event, ui) {
                        updateSpecification($(this).parents("tr").first(), ui.item.data);
                    }
                }).bind('blur', function(event) {
                    var tr = $(this).parents("tr").first();
                    var p = AllProducts[tr.find('[field="ProductSpecificationID"]').val()];
                    if (!p || [p.Name, p.Grade, p.Model].join(" ") != tr.find(".txtproduct").val()) {
                        updateSpecification(tr, null);
                    } else {
                        updateSpecification(tr, p);
                    }
                    calculateSpecification(tr, true);
                });

                $('#detailstable [field="Price"],#detailstable [field="Count"]').bind('keydown', function(event) {
                    if (event.keyCode == 13) {
                        calculateSpecification($(this).parents("tr").first(), true);
                    }
                }).bind('blur', function() {
                    calculateSpecification($(this).parents("tr").first(), true);
                });
                $('[field="HouseID"]').bind('change', getInventory);
                getPrice();
                getInventory();
            }

            $.each($('#detailstable tbody tr'), function() {
                var specId = $(this).find('[field="ProductSpecificationID"]').val();
                updateSpecification(this, AllProducts[specId], true, true);
            });
            calculateBill();
        });
    </script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:Panel ID="pnlWrapper" CssClass="billwrapper" runat="server">
        <table class="purchasebill infotable">
            <tr>
                <td>
                    <label>
                        录入日期</label>
                </td>
                <td>
                    <input type="hidden" field="ID" value="<%= this.PurchaseBill.ID%>" />
                    <input type="text" class="datepicker" field="PurchaseDate" value="<%= this.PurchaseBill.PurchaseDate.ToString("yyyy-MM-dd") %>" />
                </td>
                <td>
                    <label>
                        单据编号
                    </label>
                </td>
                <td>
                    <input type="text" field="SerialNumber" value="<%= this.PurchaseBill.SerialNumber %>" />
                </td>
            </tr>
            <tr>
                <td>
                    <label>
                        仓 库
                    </label>
                </td>
                <td>
                    <asp:DropDownList ID="ddlWareHouse" field="HouseID" runat="server" DataTextField="Name"
                        DataValueField="ID">
                    </asp:DropDownList>
                </td>
                <td>
                    <label>
                        供 货 商
                    </label>
                </td>
                <td>
                    <input type="hidden" field="SupplierID" value="<%= this.PurchaseBill.SupplierID %>" />
                    <input type="text" id="txtSupplier" />
                </td>
            </tr>
            <tr>
                <td>
                    <label>
                        经 手 人</label>
                </td>
                <td>
                    <asp:DropDownList ID="ddlTransactor" runat="server" field="Transactor" DataValueField="LoginName"
                        DataTextField="Name">
                    </asp:DropDownList>
                </td>
                <td>
                    <label>
                        摘 要
                    </label>
                </td>
                <td>
                    <input type="text" field="Summary" value="<%= this.PurchaseBill.Summary %>" />
                </td>
            </tr>
            <tr>
                <td>
                    <label>
                        附加说明
                    </label>
                </td>
                <td colspan="3">
                    <input type="text" field="Comments" value="<%= this.PurchaseBill.Comments %>" />
                </td>
            </tr>
        </table>
        <table id="detailstable" class="datatable">
            <thead>
                <tr>
                    <th class="col-sn">
                        编号
                    </th>
                    <th class="col-product">
                        产品
                    </th>
                    <th class="col-specification">
                        规格
                    </th>
                    <th class="col-unit">
                        单位
                    </th>
                    <th class="col-price">
                        <label>
                            单价</label>
                    </th>
                    <th class="col-count">
                        数量
                    </th>
                    <th class="col-amount">
                        <label>
                            金额</label>
                    </th>
                    <th class="col-comments">
                        备注
                    </th>
                </tr>
            </thead>
            <tbody>
                <asp:Repeater ID="rptDetails" runat="server">
                    <ItemTemplate>
                        <tr>
                            <td class="col-sn">
                                <%# Container.ItemIndex+1 %>
                                <input type="hidden" field="ID" value="<%# Eval("ID")%>" />
                            </td>
                            <td class="col-product">
                                <input type="hidden" field="ProductSpecificationID" value="<%# Eval("ProductSpecificationID")%>" />
                                <input type="text" class="txtproduct" value="" />
                            </td>
                            <td class="col-specification">
                                <input type="text" readonly="readonly" disabled="disabled" />
                            </td>
                            <td class="col-unit">
                                <input type="text" readonly="readonly" disabled="disabled" />
                            </td>
                            <td class="col-price">
                                <input type="text" field="Price" value="<%# Eval("Price")%>" />
                            </td>
                            <td class="col-count">
                                <input type="text" field="Count" value="<%# Eval("Count")%>" />
                            </td>
                            <td class="col-amount">
                                <input type="text" field="Amount" readonly="readonly" disabled="disabled" value="<%# Eval("Amount")%>" />
                            </td>
                            <td class="col-comments">
                                <input type="text" field="Comments" value="<%# Eval("Comments")%>" />
                            </td>
                        </tr>
                    </ItemTemplate>
                </asp:Repeater>
            </tbody>
            <tfoot>
                <tr>
                    <th>
                        合计
                    </th>
                    <th colspan="7">
                        <label>
                            数量：<input type="text" id="txtTotalCount" value="0" style="width: 100px; background: transparent;"
                                disabled="disabled" /></label>
                        <label>
                            金额：￥<input type="text" id="txtTotalAmount" value="0" style="width: 100px; background: transparent;"
                                disabled="disabled" /></label>
                    </th>
                </tr>
            </tfoot>
        </table>
        <br />
        <p>
            <asp:PlaceHolder ID="placePayment" runat="server"><span class="payment">
                <label>
                    <%=this.BillType==Warehouse.DataAccess.PurchaseBillType.Return?"收":"付" %>款账户：<asp:DropDownList
                        ID="ddlAssetAmount" runat="server" field="AccountID" DataValueField="ID" DataTextField="Name">
                    </asp:DropDownList>
                </label>
                <label>
                    <%=this.BillType==Warehouse.DataAccess.PurchaseBillType.Return?"收":"付" %>款金额：￥<input
                        type="text" field="Amount" value="<%= this.Pay.Amount %>" /></label>
            </span></asp:PlaceHolder>
            <span style="float: right;">
                <uc:AuthorityControl ID="acAddPurchase" runat="server" Action="AddBill">
                    <input type="button" class="ui-button" value="保存" onclick="addBill('AddPurchase');return false;" />
                </uc:AuthorityControl>
                <uc:AuthorityControl ID="acAddGift" runat="server" Action="AddGift">
                    <input type="button" class="ui-button" value="保存" onclick="addBill('AddGift');return false;" />
                </uc:AuthorityControl>
                <uc:AuthorityControl ID="acAddReturn" runat="server" Action="AddGift">
                    <input type="button" class="ui-button" value="保存" onclick="addBill('AddReturn');return false;" />
                </uc:AuthorityControl>
                <uc:AuthorityControl ID="acModifyPurchase" runat="server" Action="SavePurchase">
                    <input type="button" class="ui-button" value="保存" onclick="saveBill('SavePurchase');return false;" />
                    <input type="button" class="ui-button" value="作废" onclick="invalidBill('InvalidPurchase');return false;" />
                </uc:AuthorityControl>
                <uc:AuthorityControl ID="acModifyGift" runat="server" Action="SaveGift">
                    <input type="button" class="ui-button" value="保存" onclick="saveBill('SaveGift');return false;" />
                    <input type="button" class="ui-button" value="作废" onclick="invalidBill('InvalidGift');return false;" />
                </uc:AuthorityControl>
                <uc:AuthorityControl ID="acModifyReturn" runat="server" Action="SaveReturn">
                    <input type="button" class="ui-button" value="保存" onclick="saveBill('SaveReturn');return false;" />
                    <input type="button" class="ui-button" value="作废" onclick="invalidBill('InvalidReturn');return false;" />
                </uc:AuthorityControl>
                <input type="button" class="ui-button" value="取消" onclick="dialogCallback(false);return false;" />
            </span>
        </p>
    </asp:Panel>
</asp:Content>
